package cn.com.shuyangyang.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.shuyangyang.controller.response.ApplicationErrorResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.EnumStatus;
import cn.com.shuyangyang.domain.User;
import cn.com.shuyangyang.service.UserService;

/**
 * 批量导入用户
 * @author ShuYangYang
 * E-Mail:shuyangyang@aliyun.com
 * http://www.shuyangyang.com.cn
 * Date:2015年2月7日下午7:33:41
 *
 */
@Service("uploadUserData")
public class UploadUserData {
	
	Logger	logger	= LoggerFactory.getLogger(UploadUserData.class);
	
	@Autowired
	private UserService userService;
	
	public Response UploadUser(HttpServletRequest request){
		List<User> list = new ArrayList<User>();
        try {
        	// 为获取需要导入的 excel 文件，把 HttpServletRequest 转型为 MultipartHttpRequest
    		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

    		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
     
            // 获得 request 中上传的 excel 文件
            MultipartFile file = multipartRequest.getFile("fileName");
            
            if(!file.getOriginalFilename().endsWith(".xls")||!file.getOriginalFilename().endsWith(".xlsx")){
            	return new ApplicationErrorResponse("上传失败，上传文件类型错误，必须是.xls或者.xlsx文件！");
            }
            long fileSize = file.getSize();
    		if(fileSize>104857600L){
    			return new ApplicationErrorResponse("文件太大！");
    		}
            String filePath = "c:\\temp\\uploadUser\\"+file.getOriginalFilename();
            File newFile = new File(filePath);
            File parent = newFile.getParentFile(); 
            if(parent!=null&&!parent.exists()){ 
            	parent.mkdirs(); 
            } 
			file.transferTo(newFile);
			UploadUserData poi = new UploadUserData();
			list = poi.readXls(newFile);
			
			/** 一旦发现文件中有填写错误或者登录名数据库已存在情况，直接报错，不存储 */
			for(User user:list){
				String loginName = user.getLogin_name();
				User dbUser = userService.getUserByLoginName(loginName);
				if(user.getUser_status()==null){
					return new ApplicationErrorResponse("文件中登录名为（"+loginName+"）的用户状态填写错误，需要修正为AVAILABLE或者DISABLED");
				}else if(loginName.equals(dbUser!=null?dbUser.getLogin_name():null)){
					return new ApplicationErrorResponse("系统中登录名"+loginName+"已经存在，请重新上传！");
				}else{
					
				}
			}
			
			for(User user:list){
				userService.addUser(user);
			}
			
			return new NormalResponse();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			logger.error("参数错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("导入失败，系统异常！请联系技术人员");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("文件导入错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("导入失败，系统异常！请联系技术人员");
		} 
		
	}
	
	/**
     * 读取xls文件内容
     * 
     * @return List<User>对象
     * @throws IOException
     *             输入/输出(i/o)异常
     */
	public List<User> readXls(File fileName) throws IOException {
    	if(fileName==null) return null;
        InputStream is = new FileInputStream(fileName);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        User user = null;
        List<User> list = new ArrayList<User>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow == null) {
                    continue;
                }
                user = new User();
                // 循环列Cell
                // 0用户名 1登录名 2登录密码 3用户状态
                // for (int cellNum = 0; cellNum <=4; cellNum++) {
                HSSFCell userName = hssfRow.getCell(0);
                if (userName == null) {
                    continue;
                }
                user.setUser_name(getValue(userName));
                HSSFCell loginName = hssfRow.getCell(1);
                if (loginName == null) {
                    continue;
                }
                user.setLogin_name(getValue(loginName));
                HSSFCell loginPwd = hssfRow.getCell(2);
                if (loginPwd == null) {
                    continue;
                }
                user.setLogin_password(getValue(loginPwd));
                HSSFCell userStatus = hssfRow.getCell(3);
                if (userStatus == null) {
                    continue;
                }
                if(getValue(userStatus).equals("AVAILABLE")){
                	user.setUser_status(EnumStatus.AVAILABLE);
                }else if(getValue(userStatus).equals("DISABLED")){
                	user.setUser_status(EnumStatus.DISABLED);
                }else{
                	
                }
                list.add(user);
            }
        }
        return list;
    }
 
    /**
     * 得到Excel表中的值
     * 
     * @param hssfCell
     *            Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
}
